package org.example.Swing.xiangmu.login;

import org.example.Entity.Score;
import org.example.Entity.Student;
import org.example.Swing.handler.MainHandler;
import org.example.controller.GradeController;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

public class MainView extends JFrame {

    public int pageNow = 1;
    JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    JButton addBtn = new JButton("增加");
    JButton updateBtn = new JButton("修改");
    JButton delBtn = new JButton("删除");
    JTextField searchText = new JTextField(15);
    JButton searchBtn = new JButton("查询");
    JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    JButton fanBtn=new JButton("返回登录");
    JButton preBtn = new JButton("上一页");
    JButton nextBtn = new JButton("下一页");
    List<Student> students1;
    MainHandler mainHandler;
    //先创建一个空列表
    ArrayList<Object> objects = new ArrayList<>();
    DefaultTableModel model = new DefaultTableModel();
    GradeController gradeController = new GradeController();
    private final int pageSize = 5;
    private String id;
    private String scoreid;

    public MainView() {
        super("主界面-学生成绩管理系统");

        Container contentPane = getContentPane();
        mainHandler = new MainHandler(this);
        //头部
        layoutNorth(contentPane);
        //分页
        //提取数据
        JTable table = new JTable(model);

        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, cellHasFocus, row, column);
                setHorizontalAlignment(SwingConstants.CENTER);
                return this;
            }
        });
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    int selectedRow = table.getSelectedRow();
                    if (selectedRow != -1) {
                        id = model.getValueAt(selectedRow, 1).toString();
                        scoreid = model.getValueAt(selectedRow, 3).toString();
                    }
                }
            }
        });
        //底部
        layoutSouth(contentPane);

        model.addColumn("名字");
        model.addColumn("学号");
        model.addColumn("课程");
        model.addColumn("课程编号：");
        model.addColumn("成绩");
        //使用增强型for循环循环查询到的对象 先循环主对象
        updateTableData();
        //执行玩上面的代码后得到一个不同学生的成绩数组，将其循环出来添加到表格上

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(new JScrollPane(table));
        pack();
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //设置可否缩放
        setResizable(true);
        setVisible(true);
    }

    public String getSelectedScoreIds() {
        return scoreid;
    }

    public String getSelectedStudentIds() {

        return id;
    }

    //分页按钮
    private void layoutSouth(Container contentPane) {
        // 上一页
        preBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (pageNow == 1) {
                    JOptionPane.showMessageDialog(MainView.this, "已经是第一页了！");
                } else {
                    pageNow--;
                    updateTableData();
                }
            }
        });
        //下一页
        nextBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int i = gradeController.pageNumber(pageNow, pageSize);
                if (i == 0) {
                    JOptionPane.showMessageDialog(MainView.this, "已经是最后一页啦！");
                } else {
                    pageNow++;
                }
                updateTableData();
            }
        });
        fanBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                mainHandler.fanhui();
            }
        });
        southPanel.add(fanBtn);
        southPanel.add(preBtn);
        southPanel.add(nextBtn);
        contentPane.add(southPanel, BorderLayout.SOUTH);
    }

    //操作按钮
    private void layoutNorth(Container contentPane) {
        addBtn.addActionListener(mainHandler);
        updateBtn.addActionListener(mainHandler);
        delBtn.addActionListener(mainHandler);
        //查询
        searchBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!searchText.getText().equals("")) {
                    objects.clear();
                    model.setRowCount(0);
                    students1 = gradeController.selectByGradeOne(searchText.getText());
                    objects.clear();
                    for (Student student : students1) {
                        //然后从对象中抽出子对象进行循环提取数据
                        List<Score> scores = student.getScores();
                        for (Score score : scores) {
                            //创建一个Obiect类型的数组，用于接受从不同实体类方法中循环出来的所需数据追加为一个一维数组
                            Object[] row = {student.getName(), student.getStudentId(), score.getCourse().getCourseName(), score.getCourseId(), String.valueOf(score.getScores())};
                            //将一个一维数组追加到创建好的列表中
                            objects.add(row);
                        }
                    }
                    for (Object row : objects) {
                        model.addRow((Object[]) row);
                    }
                } else {
                    model.setRowCount(0);
                    updateTableData();
                    objects.clear();
                }
            }
        });
        northPanel.add(addBtn);
        northPanel.add(updateBtn);
        northPanel.add(delBtn);
        northPanel.add(searchText);
        northPanel.add(searchBtn);
        contentPane.add(northPanel, BorderLayout.NORTH);
    }

    //表单内容显示
    private void updateTableData() {
        //清空表单内容
        objects.clear();
        model.setRowCount(0);
        //数据库输出的数据
        students1 = gradeController.selectByGradeAll1(pageNow, pageSize);
        //使用增强型for循环循环查询到的对象 先循环主对象
        for (Student student : students1) {
            //然后从对象中抽出子对象进行循环提取数据
            List<Score> scores = student.getScores();
            for (Score score : scores) {
                //创建一个Obiect类型的数组，用于接受从不同实体类方法中循环出来的所需数据追加为一个一维数组
                Object[] row = {student.getName(), student.getStudentId(), score.getCourse().getCourseName(), score.getCourseId(), String.valueOf(score.getScores())};
                //将一个一维数组追加到创建好的列表中
                objects.add(row);
            }
        }
        //执行玩上面的代码后得到一个不同学生的成绩数组，将其循环出来添加到表格上
        for (Object row : objects) {
            model.addRow((Object[]) row);
        }
    }

    public JTextField getSearchText() {
        return searchText;
    }
}
